<template>
  <div class="container">
    <el-divider content-position="left"><span class="title-left-color">基本信息</span></el-divider>
    <el-form ref="formRef" :model="form" :rules="rules" v-loading="loading" label-width="150px">
      <el-row :gutter="10">
        <el-col :span="11">
          <el-form-item label="发布主体：" prop="business_school_entity_id">
            <el-select v-model.trim="form.business_school_entity_id" placeholder="发布主体">
              <el-option v-for="item in selectEntityList" :label="item.name" :value="item.id" :key="item.id"> </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="1">
          <el-button type="primary" plain @click="handleEntityRefresh">刷新</el-button>
        </el-col>
        <el-col :span="12">
          <el-form-item label="标题：" prop="title">
            <el-input v-model="form.title" placeholder="标题"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="排序：" prop="sort">
            <el-input v-model.number="form.sort" placeholder="排序"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否上架：" prop="is_show">
            <el-select v-model.trim="form.is_show" placeholder="是否上架" clearable class="">
              <el-option v-for="item in whetherStatue" :label="item.dictLabel" :value="item.dictValue" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="主图：" prop="image">
            <UploadImageInfo :imageWidth="178" :imageHeight="178" v-model:disabledbtn="disabledbtn" v-model:loading="loading" imageKey="image" v-model:form="form" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="视频：" prop="video">
            <UploaVideoInfo v-model:disabledbtn="disabledbtn" v-model:loading="loading" videoKey="video" v-model:form="form" @successCallback="successCallbackVideo" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="footer-center">
      <el-button :disabled="disabledbtn" @click="cancelSubmit">取 消</el-button>
      <el-button type="primary" :disabled="disabledbtn" v-if="!isDisabledbtn" @click="submitForm">确 定</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import UploadImageInfo from "@/components/common/UploadImageInfo.vue";
import UploaVideoInfo from "@/components/common/UploaVideoInfo.vue";
import type { postOrPutType } from "@/constants";
import type { ViewMode } from "@/types/common";
import { IMG_URL } from "@/utils/config";
import { useState } from "@/hooks/useState.ts";
import type { ISchoolEntity } from "@/types/businessSchoolManager/businessSchoolEntity";
import type { ISchoolVideoDTO } from "@/types/businessSchoolManager/businessSchoolVideo";
import type { IDictData } from "@/types/dict";
import type { IUpdateSuccessData } from "@/types/upload";
import { commonBusinessSchoolVideoInfo } from "@/utils/api/businessSchoolVideo";
const { disabledbtn, loading, toggleState } = useState();

interface Props {
  selectEntityList: Array<ISchoolEntity>;
  whetherStatue: Array<IDictData>;
}
const { selectEntityList, whetherStatue } = defineProps<Props>();
const formStatus = defineModel<ViewMode>("formStatus", { required: true });
const form = defineModel<ISchoolVideoDTO>("form", { required: true });
const emit = defineEmits<{
  handleInitData: [];
  handleSuccess: [];
  handleEntityRefresh: [];
}>();

const isDisabledbtn = ref(false);
const formRef = useTemplateRef("formRef");
const methodType = ref<postOrPutType>("PUT");

const rules = reactive({
  title: [{ required: true, message: "请填写标题", trigger: "blur" }],
  is_show: [{ required: true, message: "请选择是否上架", trigger: "blur" }],
  business_school_entity_id: [{ required: true, message: "请选择发布主体", trigger: "blur" }],
  image: [{ required: true, message: "请上传图片", trigger: "blur" }],
  video: [{ required: true, message: "请上传视频", trigger: "blur" }],
  sort: [{ required: true, message: "请填写排序", trigger: "blur" }]
});

onMounted(() => {
  console.log("Component mounted!");
});

/* formStatus处理器 */
const statusHandlers: Record<ViewMode, () => void> = {
  view: () => {
    isDisabledbtn.value = true;
  },
  edit: () => {
    methodType.value = "PUT";
  },
  add: () => {
    methodType.value = "POST";
  },
  none: () => {
    /* 初始化数据 */
    handleInitData();
  }
};
/* 监听formStatus,新增，编辑，查看的时候都可以打开模态框，又是有不同的操作和效果，需要单独判断，none为模态框关闭的情况，需要初始化数据 */
watch(formStatus, newValue => {
  const handler = statusHandlers[newValue];
  handler?.();
});

/* 刷新发布主体 */
function handleEntityRefresh() {
  emit("handleEntityRefresh");
}
/* 图片上传成功回调 */
function successCallbackVideo(data: IUpdateSuccessData) {
  const audio = new Audio(IMG_URL + "/" + data.key);
  // 元数据已加载
  audio.addEventListener("loadedmetadata", () => {
    let duration = audio.duration;
    form.value.length = Math.ceil(duration) + "";
  });
}

/* 初始化数据 */
function handleInitData() {
  methodType.value = "POST";
  isDisabledbtn.value = false;
  formRef.value?.resetFields();
  formRef.value?.clearValidate();
}

/* 保存或编辑 */
function submitForm() {
  if (!formRef.value) return;
  formRef.value.validate(valid => {
    if (!valid) {
      ElMessage.warning("请填写必填字段");
      return;
    }
    submitFormInfo();
  });
}

/* 保存或编辑信息 */
function submitFormInfo() {
  /* 防止多次提交 */
  toggleState(true);
  commonBusinessSchoolVideoInfo(form.value, methodType.value)
    .then(res => {
      ElMessage.success(res.msg);
      cancelSubmit();
      emit("handleSuccess");
    })
    .catch(() => {})
    .finally(() => {
      toggleState(false);
    });
}
/* 保存或编辑 取消提交 */
function cancelSubmit() {
  // clearData();
  // activeName = "one";
  emit("handleInitData");
}
</script>

<style lang="scss" scoped>
/* 修改select的盒模型 */
.el-select {
  display: block;
}
/* 底部按钮居中 */
.footer-center {
  margin: 10px 0;
  text-align: center;
}
</style>
